﻿using Studio77.GuessLyric.Entity;
using Studio77.GuessLyric.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Resources;

namespace Studio77.GuessLyric.Core
{
    public class StageManager
    {
        //keys
        private const string LAST_STAGE_INDEX_KEY = "LastStageKey";
        private const string IS_PLAY_SOUND_KEY = "isPlaySoundKey";
        private const string TOTALGKEY = "TotalGKey";
        private const string IndexMapKey = "IndexMapKey";
        private const string NEW_USER_TASK_KEY = "newUserTaskKey";
        private const string LAST_STAGE_COUNT_KEY = "LAST_STAGE_COUNT_KEY";
        private const string LAST_FULLSCREEN_DATE_KEY = "LAST_FULLSCREEN_DATE";
        private const string aaaeskey = "dave";
        private const string salt = "77studio";

        const int version = 1;
        public bool TurnMoka = true;

        public static StageManager Instance = new StageManager();

        private StageManager()
        {

        }

        public List<QuestionEntity> Questions { get; set; }
        public Dictionary<int, int> IndexMap { get; set; }

        private string lastFullScreenDate = "XXXXXX";
        /// <summary>
        /// 上一次显示全屏广告的日期
        /// </summary>
        public string LastFullScreenDate
        {
            get
            {
                return lastFullScreenDate;
            }
            set
            {
                lastFullScreenDate = value;
                IsolatedStorageSettings.ApplicationSettings[LAST_FULLSCREEN_DATE_KEY] = lastFullScreenDate;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int lastStageCount;
        public int LastStageCount
        {
            get
            {
                return lastStageCount;
            }
            set
            {
                lastStageCount = value;
                IsolatedStorageSettings.ApplicationSettings[LAST_STAGE_COUNT_KEY] = lastStageCount;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private bool isDoNewUserTask = false;
        public bool IsDoNewUserTask
        {
            get
            {
                return isDoNewUserTask;
            }
            set
            {
                isDoNewUserTask = value;
                IsolatedStorageSettings.ApplicationSettings[NEW_USER_TASK_KEY] = isDoNewUserTask;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private bool isPlaySound = true;

        /// <summary>
        /// 是否播放音效
        /// </summary>
        public bool IsPlaySound
        {
            get
            {
                return isPlaySound;
            }
            set
            {
                isPlaySound = value;
                IsolatedStorageSettings.ApplicationSettings[IS_PLAY_SOUND_KEY] = isPlaySound;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int lastStage = 1;
        public int LastStage
        {
            get
            {
                return lastStage;
            }
            set
            {
                lastStage = value;
                IsolatedStorageSettings.ApplicationSettings[LAST_STAGE_INDEX_KEY] = lastStage;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        private int totalG;
        public int TotalG
        {
            get
            {
                return totalG;
            }
            set
            {
                totalG = value;
                IsolatedStorageSettings.ApplicationSettings[TOTALGKEY] = totalG;
                IsolatedStorageSettings.ApplicationSettings.Save();
            }
        }

        public void Init()
        {
            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAST_STAGE_COUNT_KEY))
            {
                lastStageCount = (int)IsolatedStorageSettings.ApplicationSettings[LAST_STAGE_COUNT_KEY];
            }
            Questions = new List<QuestionEntity>();
            IndexMap = new Dictionary<int, int>();
            using (StreamReader sr = new StreamReader(Application.GetResourceStream(new Uri("Config/config.jpg", UriKind.RelativeOrAbsolute)).Stream))
            {
                string line = sr.ReadLine();
                while (!string.IsNullOrEmpty(line))
                {
                    string lineContent = AESEncryption.DecryptAES(line, aaaeskey, salt);
                    string[] component = lineContent.Split('#');

                    if (component[0] == "1")
                    {
                        //猜歌名
                        if (component.Length == 4)
                        {
                            QuestionEntity entity = new QuestionEntity()
                            {
                                Type = 1,
                                LyricStrList = component[2].Split(',').ToList(),
                                SongName = component[3],
                                Singer = component[1]
                            };
                            if (entity.SongName.Length <= 9)
                            {
                                Questions.Add(entity);
                            }
                            else
                            {
                                string iii = string.Empty;
                            }
                        }
                        else
                        {
                            throw new Exception("config配置不正确");
                        }
                    }
                    else if (component[0] == "2")
                    {
                        //猜歌词
                        if (component.Length == 5)
                        {
                            QuestionEntity entity = new QuestionEntity()
                            {
                                Type = 2,
                                SongName = component[1],
                                Singer = component[2],
                                LyricStrList = component[3].Split(',').ToList(),
                                GuessLyricIndex = Convert.ToInt32(component[4].Trim())
                            };

                            if (entity.GuessLyricIndex > entity.LyricStrList.Count || entity.GuessLyricIndex < 1)
                            {
                                throw new Exception("歌词index不正确");
                            }
                            if (entity.LyricStrList[entity.GuessLyricIndex - 1].Length <= 9 &&
                                entity.LyricStrList[entity.GuessLyricIndex - 1].IndexOf(" ") < 0)
                            {
                                Questions.Add(entity);
                            }
                            else
                            {
                                string iii = string.Empty;
                            }
                        }
                        else
                        {
                            throw new Exception("config配置不正确");
                        }
                    }
                    else
                    {
                        throw new Exception("未知的类型");
                    }
                    line = sr.ReadLine();
                }
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(IndexMapKey))
            {
                IndexMap = (Dictionary<int, int>)IsolatedStorageSettings.ApplicationSettings[IndexMapKey];
                if (Questions.Count > lastStageCount)
                {
                    //有新关卡加入，重新排列新关卡，并加入到IndexMap中
                    Random r = new Random(DateTime.Now.Millisecond);
                    List<int> templst = new List<int>();
                    for (int i = lastStageCount; i < Questions.Count; i++)
                    {
                        templst.Add(i);
                    }
                    for (int i = 0; i < (Questions.Count - lastStageCount); i++)
                    {
                        int x = r.Next(Questions.Count - lastStageCount);
                        int temp = templst[i];
                        templst[i] = templst[x];
                        templst[x] = temp;
                    }
                    for (int i = 0; i < Questions.Count - lastStageCount; i++)
                    {
                        IndexMap.Add(i + lastStageCount, templst[i]);
                    }
                    IsolatedStorageSettings.ApplicationSettings[IndexMapKey] = IndexMap;
                    IsolatedStorageSettings.ApplicationSettings.Save();
                    LastStageCount = Questions.Count;
                }
            }
            else
            {
                Random r = new Random(DateTime.Now.Millisecond);
                List<int> templst = new List<int>();
                for (int i = 0; i < Questions.Count; i++)
                {
                    templst.Add(i);
                }
                for (int i = 0; i < Questions.Count; i++)
                {
                    int x = r.Next(Questions.Count);
                    int temp = templst[i];
                    templst[i] = templst[x];
                    templst[x] = temp;
                }
                for (int i = 0; i < Questions.Count; i++)
                {
                    IndexMap.Add(i, templst[i]);
                }
                IsolatedStorageSettings.ApplicationSettings[IndexMapKey] = IndexMap;
                IsolatedStorageSettings.ApplicationSettings.Save();
                LastStageCount = Questions.Count;
            }

            if (IsolatedStorageSettings.ApplicationSettings.Contains(TOTALGKEY))
            {
                totalG = (int)IsolatedStorageSettings.ApplicationSettings[TOTALGKEY];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAST_STAGE_INDEX_KEY))
            {
                lastStage = (int)IsolatedStorageSettings.ApplicationSettings[LAST_STAGE_INDEX_KEY];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(IS_PLAY_SOUND_KEY))
            {
                isPlaySound = (bool)IsolatedStorageSettings.ApplicationSettings[IS_PLAY_SOUND_KEY];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(NEW_USER_TASK_KEY))
            {
                isDoNewUserTask = (bool)IsolatedStorageSettings.ApplicationSettings[NEW_USER_TASK_KEY];
            }
            if (IsolatedStorageSettings.ApplicationSettings.Contains(LAST_FULLSCREEN_DATE_KEY))
            {
                lastFullScreenDate = (string)IsolatedStorageSettings.ApplicationSettings[LAST_FULLSCREEN_DATE_KEY];
            }
        }

        public QuestionEntity GetQuestionInfo()
        {
            return Questions[IndexMap[lastStage - 1]];
        }

        internal bool TrunNext()
        {
            LastStage += 1;
            if (lastStage < Questions.Count - 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        public List<string> GetBeixuanDaan()
        {
            List<string> result = new List<string>();
            QuestionEntity ques = GetQuestionInfo();

            String daan = string.Empty;
            if (ques.Type == 1)
            {
                daan = ques.SongName;
            }
            else if (ques.Type == 2)
            {
                daan = ques.LyricStrList[ques.GuessLyricIndex - 1];
            }
            else if (ques.Type == 3)
            {
                daan = ques.Singer;
            }


            if (daan[0] >= 65 && daan[0] <= 97)
            {
                string beixuan = string.Empty;
                beixuan += daan;
                Random r = new Random(DateTime.Now.Millisecond);
                while (beixuan.Length < 30)
                {
                    beixuan += (char)(65 + r.Next(26));
                }
                for (int i = 0; i < 30; i++)
                {
                    result.Add(beixuan[i].ToString());
                }
            }
            else
            {

                int index = Questions.IndexOf(ques);
                Random r = new Random(DateTime.Now.Millisecond);
                //向后找，只到字符够
                string beixuan = string.Empty;
                while (true)
                {
                    String indexDaan = string.Empty;
                    if (Questions[index].Type == 1)
                    {
                        indexDaan = Questions[index].SongName;
                    }
                    else if (Questions[index].Type == 2)
                    {
                        indexDaan = Questions[index].LyricStrList[Questions[index].GuessLyricIndex - 1];
                    }
                    else if (Questions[index].Type == 3)
                    {
                        indexDaan = Questions[index].Singer;
                    }
                    if (indexDaan[0] >= 65 && indexDaan[0] <= 97)
                    {
                        index++;
                        if (index > Questions.Count - 1)
                        {
                            index = 0;
                        }
                        continue;
                    }
                    beixuan += indexDaan;
                    if (beixuan.Length >= 30)
                    {
                        break;
                    }
                    index++;
                    if (index > Questions.Count - 1)
                    {
                        index = 0;
                    }
                }
                for (int i = 0; i < 30; i++)
                {
                    result.Add(beixuan[i].ToString());
                }
            }
            return result;
        }

        internal void ReStartGame()
        {
            IndexMap.Clear();
            Random r = new Random(DateTime.Now.Millisecond);
            List<int> templst = new List<int>();
            for (int i = 0; i < Questions.Count; i++)
            {
                templst.Add(i);
            }
            for (int i = 0; i < Questions.Count / 2; i++)
            {
                int x = r.Next(Questions.Count / 2) + Questions.Count / 2;
                int temp = templst[i];
                templst[i] = templst[x];
                templst[x] = temp;
            }
            for (int i = 0; i < Questions.Count; i++)
            {
                IndexMap.Add(i, templst[i]);
            }
            IsolatedStorageSettings.ApplicationSettings[IndexMapKey] = IndexMap;
            IsolatedStorageSettings.ApplicationSettings.Save();

            LastStage = 1;

        }
    }
}
